<template>
  <div>
    <div class="search">
      <input type="text" v-model="keyWords" class="search-input" placeholder="输入城市名或拼音">
    </div>
    <div class="search-content" ref="listWrap" v-show="keyWords">
      <ul>
        <li
          class="search-item border-bottom"
          v-for="(item, key) of list"
          :key='key'
          @click="handelCityClick(item.name)"
        >{{item.name}}</li>
        <li class="search-item border-bottom" v-show="hasNoData">没有匹配到数据！</li>
      </ul>
    </div>
  </div>
</template>
<script>
import { mapMutations } from 'vuex'
import BScroll from 'better-scroll'
export default {
  name: 'CitySearch',
  props: {
    cities: Object
  },
  data () {
    return {
      keyWords: '',
      list: [],
      timer: null
    }
  },
  watch: {
    keyWords () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyWords) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        const result = []
        for (let i in this.cities) {
          this.cities[i].forEach((val) => {
            if (val.name.indexOf(this.keyWords) > -1 || val.spell.indexOf(this.keyWords) > -1) {
              result.push(val)
            }
          })
        }
        this.list = result
      }, 100)
    }

  },
  methods: {
    handelCityClick (city) {
      // this.$store.commit('changCity', city)
      this.changCity(city)
      this.$router.push('/')
    },
    ...mapMutations(['changCity'])
  },
  mounted () {
    const el = this.$refs.listWrap
    this.scroll = new BScroll(el)
  },
  computed: {
    hasNoData () {
      return !this.list.length
    }
  }
}
</script>
<style scoped lang='stylus'>
@import '~styles/varibles.styl'
.search
  height: 0.72rem
  background: $bgColor
  padding: 0.1rem
  .search-input
    height: 0.62rem
    line-height:0.62rem
    padding: 0 0.1rem
    width:100%
    text-align: center
    border-radius: 0.06rem
    box-sizing: border-box
.search-content
  position: absolute
  top: 1.78rem
  left:0
  right:0
  bottom:0
  background: #eeeeee
  z-index: 1
  overflow: hidden
  .search-item
    line-height: 0.62rem
    padding-left: 0.2rem
    background: #ffffff
</style>
